package syncer

import (
	"encoding/json"
	"gluenet/pkg/apis"
	"gluenet/pkg/meta"
	"strings"
	"time"
)

func syncerTrace(c *apis.StorageContext, interval int64) {
	var ins []meta.Instance
	if err := c.DataBase.InstanceListAll(&ins); err != nil {
		c.Logger.Warnf("list instance error %v", err)
	}
	for _, v := range ins {
		if err := updateTrace(c, v.Platform, v.Guid, interval); err != nil {
			c.Logger.Warnf("update trace error %v", err)
		}
	}
}

func updateTrace(c *apis.StorageContext, platform string, instanceGuid string, interval int64) error {
	end := time.Now().Unix()
	start := end - interval + 1
	if start > end {
		start = end
	}

	switch platform {
	case apis.PlatfromGluenets:
		var irun *meta.InstanceRunTime
		if err := c.DataBase.InstanceRuntimeGet(instanceGuid, &irun); err != nil {
			return err
		}

		containers := strings.Split(irun.Containers, "|")
		var cobj []string
		for _, vc := range containers {
			iv := strings.Split(vc, ",")
			cobj = append(cobj, iv[0])
		}

		var traces = make(map[string]interface{})
		if err := c.DataBase.GetTracesGluenets(instanceGuid, cobj, start*1000000, end*1000000, 1, traces); err != nil {
			return err
		}
		if len(traces) == 0 {
			return nil
		}

		bts, _ := json.Marshal(traces)
		if err := c.DataBase.InstanceRuntimeContainerTracesUpdate(instanceGuid, string(bts)); err != nil {
			return err
		}
	case apis.PlatfromKubernetes:
		var traces = make(map[string]interface{})
		if err := c.DataBase.GetTracesK8s(instanceGuid, start*1000000, end*1000000, 1, traces); err != nil {
			return err
		}
		if len(traces) == 0 {
			return nil
		}

		bts, _ := json.Marshal(traces)
		if err := c.DataBase.InstanceRuntimeContainerTracesUpdate(instanceGuid, string(bts)); err != nil {
			return err
		}
	}
	return nil
}
